package com.children.growth.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.children.growth.common.JwtUtil;
import com.children.growth.common.Result;
import com.children.growth.entity.VoiceLog;
import com.children.growth.service.SpeechRecognitionService;
import com.children.growth.service.VoiceLogService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import org.springframework.http.ResponseEntity;
import lombok.Data;

/**
 * 语音日志控制器
 * 
 * @author children
 * @since 1.0.0
 */
@RestController
@RequestMapping("/voice-log")
@CrossOrigin(origins = "*", maxAge = 3600)
public class VoiceLogController {

    @Autowired
    private VoiceLogService voiceLogService;

    @Autowired
    private SpeechRecognitionService speechRecognitionService;

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 更新语音日志请求体
     */
    @Data
    public static class UpdateVoiceLogRequest {
        private Long id;
        private String title;
        private String content;
        private List<String> tags;
        private String emotion; // 前端传递的是字符串
        private Integer emotionScore;
    }

    /**
     * 创建语音日志
     */
    @PostMapping("/create")
    public Result<Boolean> createVoiceLog(@RequestParam("audioFile") MultipartFile audioFile,
                                         @RequestParam("title") String title,
                                         HttpServletRequest request) {
        // 从JWT token中获取用户ID
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
        }
        
        Long userId = null;
        try {
            userId = jwtUtil.getUserIdFromToken(token);
        } catch (Exception e) {
            return Result.unauthorized("无效的认证token");
        }
        
        VoiceLog voiceLog = new VoiceLog();
        voiceLog.setTitle(title);
        voiceLog.setUserId(userId);
        voiceLog.setStatus(1);
        
        boolean success = voiceLogService.createVoiceLog(voiceLog, audioFile);
        return success ? Result.success(true) : Result.error("创建语音日志失败");
    }

    /**
     * 获取语音日志列表
     */
    @GetMapping("/list")
    public Result<Page<VoiceLog>> getVoiceLogList(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                  @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                                  @RequestParam(value = "emotion", required = false) String emotion,
                                                  @RequestParam(value = "keyword", required = false) String keyword,
                                                  @RequestParam(value = "startDate", required = false) String startDate,
                                                  @RequestParam(value = "endDate", required = false) String endDate,
                                                  HttpServletRequest request) {
        // 从JWT token中获取用户ID
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
        }
        
        Long userId = null;
        try {
            userId = jwtUtil.getUserIdFromToken(token);
        } catch (Exception e) {
            return Result.unauthorized("无效的认证token");
        }
        
        Page<VoiceLog> page = voiceLogService.getVoiceLogList(userId, pageNum, pageSize, emotion, keyword, startDate, endDate);
        return Result.success(page);
    }

    /**
     * 获取语音日志详情
     */
    @GetMapping("/{id}")
    public Result<VoiceLog> getVoiceLogById(@PathVariable Long id) {
        VoiceLog voiceLog = voiceLogService.getVoiceLogById(id);
        return voiceLog != null ? Result.success(voiceLog) : Result.error("语音日志不存在");
    }

    /**
     * 更新语音日志
     */
    @PutMapping("/update")
    public Result<Boolean> updateVoiceLog(@RequestBody UpdateVoiceLogRequest request, HttpServletRequest httpRequest) {
        // 从JWT token中获取用户ID
        String token = httpRequest.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
        }
        
        Long userId = null;
        try {
            userId = jwtUtil.getUserIdFromToken(token);
        } catch (Exception e) {
            return Result.unauthorized("无效的认证token");
        }
        
        // 获取原始语音日志
        VoiceLog originalVoiceLog = voiceLogService.getVoiceLogById(request.getId());
        if (originalVoiceLog == null) {
            return Result.error("语音日志不存在");
        }
        
        // 验证用户权限
        if (!originalVoiceLog.getUserId().equals(userId)) {
            return Result.unauthorized("无权限修改此语音日志");
        }
        
        // 更新语音日志
        VoiceLog voiceLog = new VoiceLog();
        voiceLog.setId(request.getId());
        voiceLog.setTitle(request.getTitle());
        voiceLog.setContent(request.getContent());
        
        // 处理情感字段（字符串转整数）
        if (request.getEmotion() != null && !request.getEmotion().trim().isEmpty()) {
            try {
                voiceLog.setEmotion(Integer.parseInt(request.getEmotion()));
            } catch (NumberFormatException e) {
                // 如果转换失败，保持原值
                voiceLog.setEmotion(originalVoiceLog.getEmotion());
            }
        }
        
        // 处理情感分数
        if (request.getEmotionScore() != null) {
            voiceLog.setEmotionScore(request.getEmotionScore());
        }
        
        // 处理标签数组，转换为逗号分隔的字符串
        if (request.getTags() != null && !request.getTags().isEmpty()) {
            String tagsString = String.join(",", request.getTags());
            voiceLog.setTags(tagsString);
        }
        
        boolean success = voiceLogService.updateVoiceLog(voiceLog);
        return success ? Result.success(true) : Result.error("更新语音日志失败");
    }

    /**
     * 删除语音日志
     */
    @DeleteMapping("/{id}")
    public Result<Boolean> deleteVoiceLog(@PathVariable Long id) {
        boolean success = voiceLogService.deleteVoiceLog(id);
        return success ? Result.success(true) : Result.error("删除语音日志失败");
    }

    /**
     * 语音转文字
     */
    @PostMapping("/speech-to-text")
    public Result<String> speechToText(@RequestParam("audioFile") MultipartFile audioFile) {
        try {
            System.out.println("=== 语音转文字请求 ===");
            System.out.println("文件名: " + audioFile.getOriginalFilename());
            System.out.println("文件大小: " + audioFile.getSize() + " bytes");
            System.out.println("文件类型: " + audioFile.getContentType());
            
            String text = speechRecognitionService.speechToText(audioFile);
            
            System.out.println("语音转文字结果: " + text);
            
            if (text == null || text.trim().isEmpty()) {
                return Result.error("语音转文字失败或内容为空");
            }
            
            return Result.success(text);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("语音转文字失败: " + e.getMessage());
        }
    }

    /**
     * 情感分析
     */
    @PostMapping("/analyze-emotion")
    public Result<Map<String, Object>> analyzeEmotion(@RequestParam("audioFile") MultipartFile audioFile) {
        try {
            // 先进行语音转文字
            String text = speechRecognitionService.speechToText(audioFile);
            if (text == null || text.trim().isEmpty()) {
                return Result.error("语音转文字失败或内容为空");
            }
            
            // 然后进行情感分析
            String emotion = voiceLogService.analyzeEmotion(text);
            
            // 返回更详细的结果
            Map<String, Object> result = new HashMap<>();
            result.put("text", text);
            result.put("emotion", emotion);
            result.put("emotionName", getEmotionName(emotion));
            
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("情感分析失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取情感名称
     */
    private String getEmotionName(String emotion) {
        switch (emotion) {
            case "1": return "开心";
            case "2": return "平静";
            case "3": return "难过";
            case "4": return "愤怒";
            case "5": return "焦虑";
            default: return "未知";
        }
    }

    /**
     * 获取语音统计
     */
    @GetMapping("/statistics")
    public Result<Object> getVoiceStatistics(HttpServletRequest request) {
        // 从JWT token中获取用户ID
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
        }
        
        Long userId = null;
        try {
            userId = jwtUtil.getUserIdFromToken(token);
        } catch (Exception e) {
            return Result.unauthorized("无效的认证token");
        }
        
        Object statistics = voiceLogService.getVoiceStatistics(userId);
        return Result.success(statistics);
    }

    /**
     * 测试语音识别功能
     */
    @PostMapping("/test-speech")
    public ResponseEntity<Map<String, Object>> testSpeechRecognition(@RequestParam("audio") MultipartFile audioFile) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            System.out.println("=== 测试语音识别功能 ===");
            System.out.println("文件大小: " + audioFile.getSize() + " bytes");
            System.out.println("文件类型: " + audioFile.getContentType());
            
            // 调用语音识别服务
            String result = speechRecognitionService.speechToText(audioFile);
            
            response.put("success", true);
            response.put("message", "语音识别成功");
            response.put("result", result);
            response.put("fileSize", audioFile.getSize());
            response.put("contentType", audioFile.getContentType());
            
            System.out.println("语音识别结果: " + result);
            
        } catch (Exception e) {
            e.printStackTrace();
            response.put("success", false);
            response.put("message", "语音识别失败: " + e.getMessage());
            response.put("error", e.toString());
        }
        
        return ResponseEntity.ok(response);
    }
} 